<template>
  <view class="wallet-detail-page">
    <!-- 顶部导航栏 -->
    <view class="custom-nav-bar">
      <view  class="nav-left" @click="navBack">
        <text style="font-size: 45rpx;" class="back-icon">←</text>
      </view>
      <view class="nav-title">余额明细</view>
      <view class="nav-right" @click="toggleFilterPopup">
        <text class="filter-icon">筛选</text>
      </view>
    </view>

    <!-- 余额概览卡片 -->
    <view class="balance-card">
      <view class="balance-info">
        <view class="balance-label">当前可用余额</view>
        <view class="balance-amount">
          <text class="currency">¥</text>
          <text class="amount">{{ totalBalance.toFixed(2) }}</text>
        </view>
        <view class="balance-frozen">
          冻结金额: ¥{{ frozenBalance.toFixed(2) }}
        </view>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-container">
      <view class="search-box">
        <text class="search-icon">🔍</text>
        <input 
          v-model="searchKeyword" 
          placeholder="搜索交易记录"
          @input="handleSearch"
          @confirm="handleSearch"
        />
        <text class="clear-btn" v-if="searchKeyword" @click="clearSearch">×</text>
      </view>
    </view>

    <!-- 交易类型标签 -->
    <view class="transaction-tabs">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'all' }"
        @click="switchTab('all')"
      >
        全部
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'income' }"
        @click="switchTab('income')"
      >
        收入
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'expense' }"
        @click="switchTab('expense')"
      >
        支出
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'freeze' }"
        @click="switchTab('freeze')"
      >
        冻结/解冻
      </view>
    </view>

    <!-- 交易记录列表 -->
    <view class="transaction-list">
      <!-- 日期分组 -->
      <view 
        class="date-group" 
        v-for="(transactions, date) in filteredTransactions" 
        :key="date"
      >
        <view class="group-date">{{ formatDate(date) }}</view>
        
        <!-- 交易记录项 -->
        <view 
          class="transaction-item" 
          v-for="(item, index) in transactions" 
          :key="index"
          @click="gotoTransactionDetail(item.id)"
        >
          <view class="transaction-icon" :style="{ backgroundColor: item.iconBg }">
            <text :style="{ color: item.iconColor }">{{ item.icon }}</text>
          </view>
          
          <view class="transaction-info">
            <view class="transaction-title">{{ item.title }}</view>
            <view class="transaction-time">{{ item.time }}</view>
          </view>
          
          <view class="transaction-amount" :class="item.amountClass">
            {{ item.amount > 0 ? '+' : '' }}{{ item.amount.toFixed(2) }}
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="isListEmpty && !isLoading">
        <view class="empty-icon">📜</view>
        <view class="empty-text">暂无交易记录</view>
        <view class="empty-subtext">没有找到符合条件的交易记录</view>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state" v-if="isLoading">
        <view class="loader"></view>
        <view class="loading-text">加载中...</view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && !isLoading && !isListEmpty">
      <button class="load-more-btn" @click="loadMoreTransactions">
        加载更多
      </button>
    </view>

    <!-- 筛选弹窗 -->
    <u-popup 
      :show="filterPopup" 
      mode="bottom" 
	  @close="filterPopup = false"
    
    >
      <view class="filter-popup">
        <view class="popup-header">
          <view class="popup-title">筛选交易记录</view>
          <view class="popup-close" @click="filterPopup = false">×</view>
        </view>
        
        <view class="filter-content">
          <!-- 时间范围筛选 -->
          <view class="filter-section">
            <view class="section-title">时间范围</view>
            <view class="time-options">
              <view 
                class="time-option" 
                :class="{ active: selectedTimeRange === item.value }"
                @click="selectTimeRange(item.value)"
                v-for="item in timeRangeOptions" 
                :key="item.value"
              >
                {{ item.label }}
              </view>
            </view>
          </view>
          
          <!-- 交易类型筛选 -->
          <view class="filter-section">
            <view class="section-title">交易类型</view>
            <view class="type-options">
              <view 
                class="type-option" 
                :class="{ active: selectedTypes.includes(item.value) }"
                @click="toggleType(item.value)"
                v-for="item in transactionTypeOptions" 
                :key="item.value"
              >
                {{ item.label }}
              </view>
            </view>
          </view>
        </view>
        
        <view class="filter-actions">
          <button class="reset-btn" @click="resetFilter">重置</button>
          <button class="confirm-btn" @click="applyFilter">确认筛选</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {

  data() {
    return {
      // 余额数据
      totalBalance: 8752.50,
      frozenBalance: 1247.50,
      filterPopup:false,
      // 交易记录状态
      transactions: {},
      filteredTransactions: {},
      isLoading: false,
      hasMore: true,
      currentPage: 1,
      
      // 筛选条件
      searchKeyword: '',
      activeTab: 'all',
      selectedTimeRange: 'all',
      selectedTypes: [],
      
      // 筛选选项
      timeRangeOptions: [
        { label: '全部时间', value: 'all' },
        { label: '今天', value: 'today' },
        { label: '近7天', value: '7days' },
        { label: '近30天', value: '30days' },
        { label: '本月', value: 'month' },
        { label: '上月', value: 'lastmonth' }
      ],
      
      transactionTypeOptions: [
        { label: '任务收入', value: 'task_income' },
        { label: '提现', value: 'withdraw' },
        { label: '充值', value: 'recharge' },
        { label: '任务保证金', value: 'deposit' },
        { label: '平台服务费', value: 'service_fee' },
        { label: '活动奖励', value: 'reward' }
      ]
    };
  },
  
  computed: {
    // 判断列表是否为空
    isListEmpty() {
      return Object.keys(this.filteredTransactions).length === 0;
    }
  },
  
  onLoad() {
    // 初始加载交易记录
    this.loadTransactions();
  },
  
  methods: {
    // 返回上一页
    navBack() {
      uni.navigateBack({ delta: 1 });
    },
    
    // 加载交易记录
    loadTransactions() {
      if (this.isLoading) return;
      
      this.isLoading = true;
      
      // 模拟API请求
      setTimeout(() => {
        const newTransactions = this.generateMockTransactions();
        this.transactions = this.currentPage === 1 
          ? newTransactions 
          : this.mergeTransactions(this.transactions, newTransactions);
        
        // 应用筛选
        this.applyFilters();
        
        this.isLoading = false;
        // 模拟只有3页数据
        this.hasMore = this.currentPage < 3;
      }, 1200);
    },
    
    // 加载更多交易记录
    loadMoreTransactions() {
      this.currentPage++;
      this.loadTransactions();
    },
    
    // 生成模拟交易数据
    generateMockTransactions() {
      const types = [
        { 
          type: 'task_income', 
          title: '无人机拍摄任务收入', 
          icon: '📸', 
          iconBg: '#E6F7F0', 
          iconColor: '#00B42A',
          amountClass: 'income'
        },
        { 
          type: 'withdraw', 
          title: '提现到银行卡', 
          icon: '💳', 
          iconBg: '#FFF2E8', 
          iconColor: '#FF7D00',
          amountClass: 'expense'
        },
        { 
          type: 'recharge', 
          title: '支付宝充值', 
          icon: '💰', 
          iconBg: '#E8F3FF', 
          iconColor: '#165DFF',
          amountClass: 'income'
        },
        { 
          type: 'deposit', 
          title: '任务保证金冻结', 
          icon: '🔒', 
          iconBg: '#F6F6F6', 
          iconColor: '#86909C',
          amountClass: 'freeze'
        },
        { 
          type: 'deposit', 
          title: '任务保证金解冻', 
          icon: '🔓', 
          iconBg: '#F6F6F6', 
          iconColor: '#86909C',
          amountClass: 'freeze'
        },
        { 
          type: 'service_fee', 
          title: '平台服务费用', 
          icon: '💼', 
          iconBg: '#FFF1F0', 
          iconColor: '#F5222D',
          amountClass: 'expense'
        },
        { 
          type: 'reward', 
          title: '新手任务奖励', 
          icon: '🎁', 
          iconBg: '#FFF7E6', 
          iconColor: '#FAAD14',
          amountClass: 'income'
        }
      ];
      
      const result = {};
      const days = 15; // 生成15天内的记录
      
      // 按日期分组
      for (let i = 0; i < days; i++) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        const dateStr = this.formatDateKey(date);
        
        // 每天生成1-3条记录
        const count = Math.floor(Math.random() * 3) + 1;
        result[dateStr] = [];
        
        for (let j = 0; j < count; j++) {
          const type = types[Math.floor(Math.random() * types.length)];
          let amount = (Math.random() * 1000 + 50).toFixed(2);
          
          // 根据类型确定金额正负
          if (type.amountClass === 'expense' || (type.amountClass === 'freeze' && Math.random() > 0.5)) {
            amount = -amount;
          }
          
          // 生成时间
          const hours = Math.floor(Math.random() * 12) + 9; // 9-21点
          const minutes = Math.floor(Math.random() * 60);
          const timeStr = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
          
          result[dateStr].push({
            id: `${dateStr}_${j}`,
            ...type,
            amount: parseFloat(amount),
            time: timeStr
          });
        }
      }
      
      return result;
    },
    
    // 合并交易记录
    mergeTransactions(existing, newData) {
      const merged = { ...existing };
      Object.keys(newData).forEach(date => {
        if (merged[date]) {
          merged[date] = [...merged[date], ...newData[date]];
        } else {
          merged[date] = newData[date];
        }
      });
      return merged;
    },
    
    // 应用所有筛选条件
    applyFilters() {
      let result = { ...this.transactions };
      
      // 1. 标签筛选
      if (this.activeTab !== 'all') {
        Object.keys(result).forEach(date => {
          result[date] = result[date].filter(item => {
            if (this.activeTab === 'income') return item.amount > 0;
            if (this.activeTab === 'expense') return item.amount < 0;
            if (this.activeTab === 'freeze') return item.amountClass === 'freeze';
            return true;
          });
          
          // 如果该日期下没有符合条件的记录，移除该日期
          if (result[date].length === 0) {
            delete result[date];
          }
        });
      }
      
      // 2. 搜索筛选
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        Object.keys(result).forEach(date => {
          result[date] = result[date].filter(item => 
            item.title.toLowerCase().includes(keyword)
          );
          
          if (result[date].length === 0) {
            delete result[date];
          }
        });
      }
      
      // 3. 时间范围筛选
      if (this.selectedTimeRange !== 'all') {
        const now = new Date();
        const cutoffDate = new Date();
        
        switch (this.selectedTimeRange) {
          case 'today':
            cutoffDate.setHours(0, 0, 0, 0);
            break;
          case '7days':
            cutoffDate.setDate(now.getDate() - 7);
            break;
          case '30days':
            cutoffDate.setDate(now.getDate() - 30);
            break;
          case 'month':
            cutoffDate.setDate(1);
            cutoffDate.setHours(0, 0, 0, 0);
            break;
          case 'lastmonth':
            cutoffDate.setMonth(now.getMonth() - 1);
            cutoffDate.setDate(1);
            cutoffDate.setHours(0, 0, 0, 0);
            const lastDay = new Date(cutoffDate.getFullYear(), cutoffDate.getMonth() + 1, 0);
            if (now > lastDay) {
              now.setTime(lastDay.getTime());
              now.setHours(23, 59, 59, 999);
            }
            break;
        }
        
        Object.keys(result).forEach(dateStr => {
          const dateParts = dateStr.split('-');
          const date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
          
          if (date < cutoffDate || date > now) {
            delete result[dateStr];
          }
        });
      }
      
      // 4. 交易类型筛选
      if (this.selectedTypes.length > 0) {
        Object.keys(result).forEach(date => {
          result[date] = result[date].filter(item => 
            this.selectedTypes.includes(item.type)
          );
          
          if (result[date].length === 0) {
            delete result[date];
          }
        });
      }
      
      this.filteredTransactions = result;
    },
    
    // 切换标签筛选
    switchTab(tab) {
      this.activeTab = tab;
      this.applyFilters();
    },
    
    // 处理搜索
    handleSearch() {
      this.applyFilters();
    },
    
    // 清除搜索
    clearSearch() {
      this.searchKeyword = '';
      this.applyFilters();
    },
    
    // 切换筛选弹窗
    toggleFilterPopup() {
      this.filterPopup = true;
    },
    
    // 选择时间范围
    selectTimeRange(value) {
      this.selectedTimeRange = value;
    },
    
    // 切换交易类型选择
    toggleType(value) {
      const index = this.selectedTypes.indexOf(value);
      if (index > -1) {
        this.selectedTypes.splice(index, 1);
      } else {
        this.selectedTypes.push(value);
      }
    },
    
    // 重置筛选条件
    resetFilter() {
      this.selectedTimeRange = 'all';
      this.selectedTypes = [];
    },
    
    // 应用筛选条件
    applyFilter() {
      this.applyFilters();
      this.toggleFilterPopup();
    },
    
    // 格式化日期显示
    formatDate(dateStr) {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      const yesterday = new Date(today);
      yesterday.setDate(today.getDate() - 1);
      
      const dateParts = dateStr.split('-');
      const date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
      
      if (date.getTime() === today.getTime()) {
        return '今天';
      } else if (date.getTime() === yesterday.getTime()) {
        return '昨天';
      } else {
        return `${dateParts[1]}月${dateParts[2]}日`;
      }
    },
    
    // 生成日期键
    formatDateKey(date) {
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    
    // 导航到充值页面
    gotoRecharge() {
      uni.navigateTo({ url: '/pages/user/recharge' });
    },
    
    // 导航到提现页面
    gotoWithdraw() {
      if (this.totalBalance <= 0) return;
      uni.navigateTo({ url: '/pages/user/withdraw' });
    },
    
    // 导航到交易详情
    gotoTransactionDetail(id) {
      uni.navigateTo({ url: `/pages/user/transaction-detail?id=${id}` });
    }
  }
};
</script>

<style scoped lang="scss">
// 颜色变量
$primary-color: #165DFF;
$primary-dark: #0E42D2;
$success-color: #00B42A;
$warning-color: #FAAD14;
$danger-color: #F5222D;
$freeze-color: #86909C;
$text-primary: #1D2129;
$text-secondary: #4E5969;
$text-tertiary: #86909C;
$background: #F5F7FA;
$card-bg: #FFFFFF;
$border-color: #E5E6EB;

.wallet-detail-page {
  background-color: $background;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  padding-top: var(--status-bar-height);
}

// 自定义导航栏
.custom-nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 90rpx;
  padding: 0 30rpx;
  background-color: $card-bg;
  border-bottom: 1px solid $border-color;
  
  .nav-left, .nav-right {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .back-icon {
    font-size: 36rpx;
    color: $text-primary;
  }
  
  .filter-icon {
    font-size: 28rpx;
    color: $text-primary;
  }
  
  .nav-title {
    font-size: 34rpx;
    font-weight: 600;
    color: $text-primary;
  }
}

// 余额卡片
.balance-card {
  background-color: $card-bg;
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.06);
  display: flex;
  flex-direction: column;
  
  .balance-info {
    margin-bottom: 25rpx;
    
    .balance-label {
      font-size: 26rpx;
      color: $text-tertiary;
      margin-bottom: 15rpx;
    }
    
    .balance-amount {
      display: flex;
      align-items: baseline;
      
      .currency {
        font-size: 32rpx;
        color: $primary-dark;
        margin-right: 5rpx;
      }
      
      .amount {
        font-size: 54rpx;
        font-weight: 700;
        color: $primary-dark;
      }
    }
    
    .balance-frozen {
      font-size: 24rpx;
      color: $text-tertiary;
      margin-top: 10rpx;
    }
  }
  
  .balance-actions {
    display: flex;
    gap: 20rpx;
    
    .action-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
      font-weight: 500;
    }
    
    .recharge-btn {
      background-color: #F0F5FF;
      color: $primary-color;
      border: 1px solid $primary-color;
    }
    
    .withdraw-btn {
      background-color: $primary-color;
      color: #fff;
      border: none;
      box-shadow: 0 4rpx 12rpx rgba(22, 93, 255, 0.25);
    }
    
    .withdraw-btn:disabled {
      background-color: #C9CDD4;
      color: #fff;
      box-shadow: none;
    }
  }
}

// 搜索框
.search-container {
  padding: 0 20rpx;
  margin-bottom: 15rpx;
  
  .search-box {
    display: flex;
    align-items: center;
    background-color: $card-bg;
    border-radius: 35rpx;
    padding: 0 20rpx;
    height: 70rpx;
    box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
    
    .search-icon {
      font-size: 28rpx;
      color: $text-tertiary;
      margin-right: 10rpx;
    }
    
    input {
      flex: 1;
      height: 100%;
      font-size: 26rpx;
      background: transparent;
      border: none;
      outline: none;
    }
    
    input::placeholder {
      color: $text-tertiary;
    }
    
    .clear-btn {
      font-size: 26rpx;
      color: $text-tertiary;
      width: 36rpx;
      height: 36rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background-color: rgba(0,0,0,0.05);
    }
  }
}

// 交易类型标签
.transaction-tabs {
  display: flex;
  padding: 0 20rpx;
  margin-bottom: 15rpx;
  overflow-x: auto;
  white-space: nowrap;
  scrollbar-width: none;
  
  &::-webkit-scrollbar {
    display: none;
  }
  
  .tab-item {
    padding: 12rpx 25rpx;
    margin-right: 10rpx;
    background-color: $card-bg;
    border-radius: 25rpx;
    font-size: 26rpx;
    color: $text-secondary;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
    flex-shrink: 0;
    
    &.active {
      background-color: $primary-color;
      color: #fff;
    }
  }
}

// 交易记录列表
.transaction-list {
  padding: 0 20rpx;
  
  .date-group {
    margin-bottom: 25rpx;
    
    .group-date {
      font-size: 24rpx;
      color: $text-tertiary;
      padding: 15rpx 0;
      border-bottom: 1px solid $border-color;
      margin-bottom: 10rpx;
    }
  }
  
  .transaction-item {
    display: flex;
    align-items: center;
    padding: 20rpx 15rpx;
    background-color: $card-bg;
    border-radius: 16rpx;
    margin-bottom: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
    transition: transform 0.2s;
    
    &:active {
      transform: scale(0.99);
    }
    
    .transaction-icon {
      width: 60rpx;
      height: 60rpx;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30rpx;
      margin-right: 20rpx;
    }
    
    .transaction-info {
      flex: 1;
      
      .transaction-title {
        font-size: 28rpx;
        color: $text-primary;
        margin-bottom: 5rpx;
        font-weight: 500;
      }
      
      .transaction-time {
        font-size: 22rpx;
        color: $text-tertiary;
      }
    }
    
    .transaction-amount {
      font-size: 28rpx;
      font-weight: 500;
      
      &.income {
        color: $success-color;
      }
      
      &.expense {
        color: $danger-color;
      }
      
      &.freeze {
        color: $freeze-color;
      }
    }
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 150rpx 0;
  
  .empty-icon {
    font-size: 80rpx;
    color: $text-tertiary;
    margin-bottom: 30rpx;
    opacity: 0.6;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: $text-secondary;
    margin-bottom: 10rpx;
  }
  
  .empty-subtext {
    font-size: 24rpx;
    color: $text-tertiary;
  }
}

// 加载状态
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  .loader {
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid rgba(22, 93, 255, 0.2);
    border-radius: 50%;
    border-top-color: $primary-color;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
  }
  
  .loading-text {
    font-size: 24rpx;
    color: $text-tertiary;
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

// 加载更多
.load-more {
  padding: 30rpx 0;
  display: flex;
  justify-content: center;
  
  .load-more-btn {
    padding: 12rpx 40rpx;
    background-color: $card-bg;
    color: $primary-color;
    border: 1px solid $primary-color;
    border-radius: 25rpx;
    font-size: 26rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
  }
}

// 筛选弹窗
.filter-popup {
  height: 100%;
  background-color: $card-bg;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  overflow-y: auto;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 25rpx 30rpx;
    border-bottom: 1px solid $border-color;
    
    .popup-title {
      font-size: 30rpx;
      font-weight: 600;
      color: $text-primary;
    }
    
    .popup-close {
      font-size: 36rpx;
      color: $text-tertiary;
      width: 50rpx;
      height: 50rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  
  .filter-content {
    padding: 30rpx;
    
    .filter-section {
      margin-bottom: 35rpx;
      
      .section-title {
        font-size: 28rpx;
        font-weight: 600;
        color: $text-primary;
        margin-bottom: 20rpx;
      }
      
      .time-options, .type-options {
        display: flex;
        flex-wrap: wrap;
        gap: 15rpx;
      }
      
      .time-option, .type-option {
        padding: 12rpx 22rpx;
        background-color: $background;
        border-radius: 8rpx;
        font-size: 24rpx;
        color: $text-secondary;
        flex-shrink: 0;
        
        &.active {
          background-color: $primary-color;
          color: #fff;
        }
      }
    }
  }
  
  .filter-actions {
    display: flex;
    gap: 20rpx;
    padding: 20rpx 30rpx;
    border-top: 1px solid $border-color;
    
    .reset-btn, .confirm-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
      font-weight: 500;
    }
    
    .reset-btn {
      background-color: $background;
      color: $text-secondary;
      border: none;
    }
    
    .confirm-btn {
      background-color: $primary-color;
      color: #fff;
      border: none;
    }
  }
}
</style>
    